<?php

namespace app\api\controller;

use app\common\controller\ApiBase;
use app\model\DistributionSetting;
use app\model\GoodsInfo;
use app\model\Order;
use app\model\OrderInfo;
use app\model\User;
use app\model\UserBalanceLog;
use app\model\UserBalanceWithdrawalLogModel;
use app\model\Withdrawal;
use app\model\WithdrawalAuto;
use app\service\GoodsService;
use app\service\OrderService;
use app\service\WxPayService;
use Exception;
use libs\Redis;
use think\Db;
use think\facade\Log;
use Wechat\CommerceApp;

class Notify extends ApiBase
{
	/**
	 * 推客微信回调
	 */
	public function tk_notify()
	{
		try {
			Log::init([
				'type'      => 'file',
				'path'      => app()->getRootPath() . 'runtime/log/tuike/',
				'level'     => ['error', 'sql', 'alert'],
				'max_files' => 10,
				'file_size' => 1024 * 1024 * 100,
			]);
			$data = $this->request->param();
			//设置回调
			if (!empty($data['echostr'])) {
				echo $data['echostr'];
				exit;
			}
			$msg   = CommerceApp::getInstance()->decryptNotifyMsg($data);
			$msg   = json_decode($msg, true);
			$event = $msg['Event'] ?? '';
			$redis = Redis::getRedis();
			switch ($event) {
				case 'head_supplier_commission_order_update':
					Log::alert("================微信回调订单数据=================");
					Log::alert($msg);
					Log::alert("================微信回调订单数据=================");
					$order_info = $msg['order_info'] ?? [];
					$order_id   = $order_info['order_id'];
					try {
						if ($order_info) {
							$UserBalanceLogModel = new UserBalanceLog();
							$sku_id              = $order_info['sku_id'];
							$order_status        = $order_info['order_status'];
							$commission_status   = $order_info['commission_order_status'];
							//订单状态为待付款则新增订单
							if ($order_status == 10) {
								if (!$redis->hexists('wx_order', $order_id)) {
									$redis->hset('wx_order', $order_id, 1);
									[$save, $info_save, $commission_log, $puser_commission_log] = OrderService::createOrderSaveData($order_id, $sku_id);
									$order_id = 0;
									if ($save) {
										$res      = Order::create($save);
										$order_id = $res->id;
										//把用户设置为老用户
										User::where('id', $save['user_id'])->update([
											'is_new' => 0,
										]);
									}
									if ($info_save) {
										$info_save['order_id'] = $order_id;
										OrderInfo::create($info_save);
									}
									// 佣金记录

									if ($commission_log) {
										$UserBalanceLogModel->create($commission_log);
									}
									if ($puser_commission_log) {
										$UserBalanceLogModel->create($puser_commission_log);
									}

									$redis->hdel('wx_order', $order_id);
								}
							} else {
								//佣金已完成，更新用户余额
								if ($order_status == 100 && $commission_status == 100) {
									$res = OrderService::updateUserBalance($order_id);
									if (!$res) {
										Log::error('更新用户余额失败：' . $order_id);
										return 'fail';
									}
								}
								// 更新佣金记录状态
								$UserBalanceLogModel->where('order_id', $order_id)->update(['status' => $commission_status]);

								Order::where('order_id', $order_id)->update([
									'status'            => $order_status,
									'commission_status' => $commission_status,
								]);
							}
						}
					} catch (Exception $e) {
						Log::error("订单处理异常：" . $e->getMessage());
						$redis->hdel('wx_order', $order_id);
					}
					break;
				case 'head_supplier_item_update':
					Log::alert("================微信回调商品数据=================");
					Log::alert($msg);
					Log::alert("================微信回调商品数据=================");
					$item_info = $msg['item_info'] ?? [];
					if ($item_info) {
						$event_type = $item_info['event_type'];
						//TODO: 更新商品，暂时不处理新增商品，只通过同步方式新增商品
						if ($event_type == 2) {
							$goods_info  = null;
							$product_id  = $item_info['product_id'];
							$shop_id     = $item_info['appid'];
							$setting     = DistributionSetting::getLevelInfo(1, 1);
							$share_ratio = $setting['ratio'] ?? 0;

							$db_goods = \app\model\Goods::field('id, status, plan_type, head_supplier_appid')->where('product_id', $product_id)->where('shop_appid', $shop_id)->find();
							try {
								[$goods, $goods_info] = GoodsService::createGoodsSaveData($shop_id, $product_id, $db_goods['plan_type'], $db_goods['head_supplier_appid'], $share_ratio);
								$save       = $goods;
								$save['id'] = $db_goods['id'];
							} catch (Exception $e) {
								$save = [
									'id'     => $db_goods['id'],
									'status' => 2,
								];
							}
							if ($save) {
								(new \app\model\Goods())->save($save);
							}
							if ($goods_info) {
								GoodsInfo::where('product_id', $product_id)->update($goods_info);
							}
						}
					}
					break;
				default:
					break;
			}
			return 'success';
		} catch (Exception $e) {
			Log::error($e->getMessage());
		}
	}

	public function wxpay()
	{
		Log::init([
			'type'      => 'file',
			'path'      => app()->getRootPath() . 'runtime/log/payNotify/',
			'level'     => ['info', 'error', 'sql', 'alert'],
			'max_files' => 10,
			'file_size' => 1024 * 1024 * 100,
		]);

		try {

			$notify_res = WxPayService::getInstance()->notify();
			$log        = [
				'msg'  => '微信支付回调成功',
				'data' => [
					'notify' => $notify_res,
				],
			];
			Log::info($log);

			$event_type = $notify_res['event_type'];
			$resource   = $notify_res['resource'];
			switch ($event_type) {
				case 'MCHTRANSFER.BILL.FINISHED':
					$state            = $resource['ciphertext']['state'];
					$out_bill_no      = $resource['ciphertext']['out_bill_no'];
					$transfer_bill_no = $resource['ciphertext']['transfer_bill_no'];
					switch ($state) {
						case 'SUCCESS':
						case 'TRANSFERING':
							$withdrawal_status = 2;
							$auto_status       = 1;
							break;
						case 'CANCELLED':
						case 'CANCELING':
							$withdrawal_status = 5;
							$auto_status       = 3;
							break;
						default:
							$withdrawal_status = 6;
							$auto_status       = 2;
							break;
					}

					$balanceLog               = UserBalanceLog::where('order_id', $out_bill_no)->find();
					$userBalanceWithdrawalLog = [];
					if (empty($balanceLog)) {
						$userBalanceWithdrawalLog = UserBalanceWithdrawalLogModel::where('order_no', $out_bill_no)
							->where('status', UserBalanceWithdrawalLogModel::STATUS_WAIT)
							->find();
						if (empty($userBalanceWithdrawalLog)) {
							Log::error("订单号：{$out_bill_no} 未查询到订单号对应的数据");
							return;
						}
						$balanceLog = UserBalanceLog::where('log_id', $userBalanceWithdrawalLog['user_balance_id'])->find();
					}

					if ($balanceLog) {
						DB::transaction(function () use ($balanceLog, $userBalanceWithdrawalLog, $auto_status, $transfer_bill_no, $out_bill_no, $withdrawal_status) {

							// 判断是否为手动提现
							$withdrawalData = WithdrawalAuto::where('order_no', $out_bill_no)->find();
							if ($withdrawalData['id']) {
								Withdrawal::where('id', $withdrawalData['id'])->update([
									'status'            => 1,
									'withdrawal_status' => $withdrawal_status,
								]);
								WithdrawalAuto::where('order_no', $out_bill_no)->update([
									'status' => $auto_status,
								]);
								// 如果未提现成功，则将返还已经扣减的用户余额
								if ($withdrawal_status !== Withdrawal::WITHDRAWAL_STATUS_COMPLETED) {
									// 返还已经扣减的用户余额
									$incMoney = intval($withdrawalData['withdrawal_money'] * 100);
									User::where('id', $withdrawalData['user_id'])->setInc('money', $incMoney);
								}
							}

							// 更新佣金记录状态
							UserBalanceLog::where('log_id', $balanceLog['log_id'])->update(['account_status' => $auto_status, 'status' => 100]);

							// 更新佣金转账记录状态
							if (!empty($userBalanceWithdrawalLog)) {
								UserBalanceWithdrawalLogModel::where('id', $userBalanceWithdrawalLog['id'])
									->update([
										'status'           => $auto_status,
										'transfer_bill_no' => $transfer_bill_no,
									]);
							}

							$user = User::where('id', $balanceLog['user_id'])->find();
							if ($user) {
								$time = time();

								$account = [
									'name'  => $user['nickname'],
									'money' => $balanceLog['money'] * 100,
									'image' => '',
								];
								Withdrawal::create([
									'user_id'           => $user['id'],
									'type'              => 1,
									'name'              => $user['nickname'],
									'withdrawal_money'  => $balanceLog['money'] * 100,
									'money'             => $balanceLog['money'] * 100,
									'withdrawal_charge' => 0,
									'charge_money'      => 0,
									'image'             => '',
									'account'           => json_encode($account, JSON_UNESCAPED_UNICODE),
									'channel'           => 1,
									'status'            => 1,
									'withdrawal_status' => 2,
									'year'              => date('Y', $time),
									'month'             => date('n', $time),
									'day'               => date('j', $time),
									'before_money'      => $user['money'],
									'after_money'       => $user['money'],
								]);
							}
						});
					}

					break;
			}
		} catch (Exception $e) {
			Log::error('处理回调失败：' . $e->getMessage());
			exit;
		}
		WxPayService::getInstance()->getApp()->success();
	}
}
